<template>
  <div class="add">
    <router-header title="报销申请"></router-header>

    <el-form ref="form" :model="form" :rules="rules" label-width="90px">
      <el-form-item label="报销部门" prop="department">
        <el-input v-model="form.department" placeholder="请输入报销部门" />
      </el-form-item>
      <el-form-item label="报销人" prop="submitPeople">
        <el-input v-model="form.submitPeople" placeholder="请输入" />
      </el-form-item>
      <div class="flex" style="margin-bottom: 10px">
        <div class="table-title">报销明细</div>
        <div>
          <el-button type="primary" size="mini" @click="addDialog = true"
            >新建</el-button
          >
        </div>
      </div>
      <el-table
        size="mini"
        header-cell-class-name="table-header-gray"
        ref="table_add"
        :data="tableList"
        border
        style="margin-bottom: 20px"
      >
        <el-table-column
          label="序号"
          header-align="center"
          align="center"
          type="index"
          width="55px"
        />
        <el-table-column label="费用类型" prop="createTime">
          <template slot-scope="{ row }">
            {{ row.expenseType | expenseTypeFilter }}
          </template>
        </el-table-column>
        <el-table-column label="报销金额(元)" prop="amount" />
        <el-table-column label="关联项目" prop="projectName"></el-table-column>
        <el-table-column label="摘要" prop="abstracts" />
        <el-table-column label="操作" width="150" fixed="right">
          <template slot-scope="{ row,$index }">
            <el-button type="text" size="mini" @click="handleClickEdit(row)">
              编辑
            </el-button>
            <el-button type="text" size="mini" class="table-btn error" @click="handleClickDel($index)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-form-item label="金额合计" prop="totalAmount">
        <el-input readonly v-model="form.totalAmount"></el-input>
      </el-form-item>
      <el-form-item label="预支费用" prop="prepaid">
        <el-input v-model="form.prepaid" oninput="value=value.replace(/^\.+|[^\d.]/g,'')"></el-input>
      </el-form-item>
      <el-form-item label="退回金额" prop="refund">
        <el-input v-model="form.refund"></el-input>
      </el-form-item>
      <el-form-item label="补领金额" prop="compensate">
        <el-input v-model="form.compensate"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="memo">
        <el-input
          type="textarea"
          rows="2"
          v-model="form.memo"
          placeholder="备注"
        />
      </el-form-item>
      <el-form-item label="附件上传" prop="reason">
          <el-upload
            class="upload-demo"
            drag
            multiple
            accept='.jpg,.gif,.png,.jpeg,.txt,.pdf,.doc,.docx,.xls,.xlsx'
            :action="upload.url"
            :headers="upload.headers"
            ref="upload"
            :auto-upload="true"
            :file-list="fileList"
            :on-change="changeFile"
            :on-remove="removeFile"
            :on-success="handleFileSuccess"
            name="uploadFile"
            :data="{ fieldName: 'imgTu', asImage: true }"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <!-- <div class="el-upload__tip" slot="tip">
              只能上传jpg/png文件，且不超过500kb
            </div> -->
          </el-upload>
        </el-form-item>
    </el-form>
    <div style="text-align: right">
      <el-button type="primary" @click="handleClickSubmit">提交</el-button>
    </div>
    <!-- 报销明细 -->
    <el-dialog
      title="报销明细"
      :visible.sync="addDialog"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="handleCloseDialog"
    >
      <el-row>
        <el-form
          ref="addForm"
          :model="addForm"
          :rules="addFormRules"
          label-width="80px"
        >
          <el-col :span="12">
            <el-form-item label="关联类型" prop="projectState">
              <el-select
                v-model="addForm.projectState"
                @change="handleChangeType"
              >
                <el-option label="项目" value="项目"></el-option>
                <el-option label="商机" value="商机"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联项目" prop="projectId">
              <el-select v-model="addForm.projectId" >
                <el-option
                  v-for="item in selectList"
                  :key="item.id"
                  :label="item.businessTypeName || item.projectName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="费用类型" prop="expenseType">
              <el-select v-model="addForm.expenseType" @change="handleChangeExpenseType">
                <el-option label="差旅费" :value="1"></el-option>
                <el-option label="交通费" :value="2"></el-option>
                <el-option label="招待费" :value="3"></el-option>
                <el-option label="行政办公" :value="4"></el-option>
                <el-option label="市场费" :value="5"></el-option>
                <el-option label="专家评审费" :value="6"></el-option>
                <el-option label="汽车费用" :value="7"></el-option>
                <el-option label="其它" :value="8"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="费用明细" prop="submitSort">
              <el-select v-model="addForm.submitSort" v-if="addForm.expenseType==null">
              </el-select>
              <el-select v-model="addForm.submitSort" v-if="addForm.expenseType==1">
                <el-option
                  v-for="item in travelTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                ></el-option>
              </el-select>
              <el-select v-model="addForm.submitSort" v-if="addForm.expenseType==2">
                <el-option
                  v-for="item in trafficTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                ></el-option>
              </el-select>
              <el-select v-model="addForm.submitSort" v-if="addForm.expenseType==3">
                <el-option
                  v-for="item in entertainTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                ></el-option>
              </el-select>
              <el-select v-model="addForm.submitSort" v-if="addForm.expenseType==4">
                <el-option
                  v-for="item in officeTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                ></el-option>
              </el-select>
              <el-select v-model="addForm.submitSort" v-if="addForm.expenseType==5">
                <el-option
                  v-for="item in marketTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                ></el-option>
              </el-select>
              <el-select v-model="addForm.submitSort" v-if="addForm.expenseType==6">
                <el-option
                  v-for="item in expertTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                ></el-option>
              </el-select>
              <el-select v-model="addForm.submitSort" v-if="addForm.expenseType==7">
                <el-option
                  v-for="item in carTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                ></el-option>
              </el-select>
              <el-select v-model="addForm.submitSort" v-if="addForm.expenseType==8">
                <el-option
                  v-for="item in otherTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="金额" prop="amount">
              <el-input
                placeholder="金额"
                v-model="addForm.amount"
                oninput="value=value.replace(/^\.+|[^\d.]/g,'')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="摘要" prop="abstracts">
              <el-input
                type="textarea"
                rows="2"
                v-model="addForm.abstracts"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click.stop="detailedSubmitForm"
          >保 存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { Reimbursement } from '@/api/approve.js';
import { getToken } from '@/utils'
import requestUrl from '@/core/http/requestUrl';

export default {
  name: 'ReimbursementAdd',
  data () {
    return {
      form: {
        totalAmount: 0
      },
      fileList: [],
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: getToken() },
        // 上传的地址
        url: requestUrl('admin/app/submit/upload')
      },

      tableList: [],
      // 项目  商机列表
      projectList: [],
      businessList: [],
      selectList: [],
      travelTypeList: [
        {value: '1', label: '飞机票'},
        {value: '2', label: '火车票'},
        {value: '3', label: '的士票'},
        {value: '4', label: '停车费'},
        {value: '5', label: '住宿费'},
        {value: '6', label: '汽油费'},
        {value: '7', label: '差旅补助'},
        {value: '8', label: '过路过桥费'}
      ],
      trafficTypeList: [
        {value: '1', label: '市内交通费'},
        {value: '2', label: '停车费'},
        {value: '3', label: '汽油费'}
      ],
      entertainTypeList: [
        {value: '1', label: '餐饮费'},
        {value: '2', label: '礼品费'},
        {value: '3', label: '住宿费'},
        {value: '4', label: '酒水费'}
      ],
      officeTypeList: [
        {value: '1', label: '耗材费'},
        {value: '2', label: '邮寄费'},
        {value: '3', label: '食品费'},
        {value: '4', label: '印刷费'},
        {value: '5', label: '培训费'},
        {value: '6', label: '会议费'},
        {value: '7', label: '宣传费'},
        {value: '8', label: '通讯费'},
        {value: '9', label: '水电暖费'},
        {value: '10', label: '装修费'},
        {value: '11', label: '物业费'},
        {value: '12', label: '教育经费'},
        {value: '13', label: '会费'},
        {value: '14', label: '人力资源费'},
        {value: '15', label: '审计费'},
        {value: '16', label: '咨询费'},
        {value: '17', label: '其他日常费'}
      ],
      marketTypeList: [
        {value: '1', label: '咨询费'},
        {value: '2', label: '服务费'},
        {value: '3', label: '其他费用'}
      ],
      expertTypeList: [
        {value: '1', label: '专家评审费'}
      ],
      carTypeList: [
        {value: '1', label: '油费'},
        {value: '2', label: '过路费'},
        {value: '3', label: '停车费'},
        {value: '4', label: '保养费'}
      ],
      otherTypeList: [
        {value: '1', label: '其他'}
      ],
      // 必填项
      rules: {
        department: [
          {
            required: true,
            message: '请输入'
          }
        ],
        submitPeople: [
          {
            required: true,
            message: '请输入'
          }
        ],
        prepaid: [
          {
            required: true,
            message: '请输入'
          }
        ]
      },
      addDialog: false,
      addForm: {},
      addFormRules: {
        projectState: [
          {
            required: true,
            message: '请选择关联类型'
          }
        ],
        projectId: [
          {
            required: true,
            message: '请选择关联项目'
          }
        ],
        expenseType: [
          {
            required: true,
            message: '请选择费用类型'
          }
        ],
        amount: [
          {
            required: true,
            message: '请输入金额'
          }
        ]
      }
    };
  },
  filters: {
    expenseTypeFilter (type) {
      const data = {
        1: '差旅费',
        2: '交通费',
        3: '招待费',
        4: '行政办公',
        5: '市场费',
        6: '专家评审费',
        7: '汽车费用',
        8: '其它'
      };
      return data[type];
    }
  },
  watch: {
    tableList (val) {
      if (val.length > 0) {
        let total = 0
        val.forEach(item => {
          total += Number(item.amount)
        })
        this.form.totalAmount = total
      } else {
        this.form.totalAmount = 0
      }
    },
    refund (val) {
      if (val >= 0) {
        this.form.compensate = val
        this.form.refund = 0
      }
      if (val <= 0) {
        this.form.refund = Math.abs(val)
        this.form.compensate = 0
      }
    }
  },
  computed: {
    // 退回/补领
    refund () {
      if (!this.form.totalAmount) return 0
      return this.form.totalAmount - this.form.prepaid
    }
  },
  created () {
  },
  methods: {
    // 项目 商业切换
    handleChangeType (val) {
      if (val === '项目') {
        this.getProjectList();
      }
      if (val === '商机') {
        this.getBusinessList();
      }
    },
    // handleChangeProject (val) {
    //   // if (this.addForm.projectState === '项目') {
    //   //   let info = this.selectList.filter(item => {
    //   //     return item.id === val
    //   //   })
    //   //   this.form.projectName = info[0].projectCode
    //   //   console.log(info)
    //   // }
    // },
    /*
    ** 费用类型下拉
     */
    handleChangeExpenseType (val) {
      this.addForm.expenseType = val
    },
    // 项目下拉
    getProjectList () {
      if (this.projectList.length > 0) {
        this.selectList = this.projectList;
        return;
      }
      Reimbursement.project(this, {}).then((res) => {
        this.projectList = res.data;
        this.selectList = res.data;
      });
    },
    // 商业下拉
    getBusinessList () {
      if (this.businessList.length > 0) {
        this.selectList = this.businessList;
        return;
      }
      Reimbursement.business(this, {}).then((res) => {
        this.businessList = res.data.records;
        this.selectList = res.data.records;
      });
    },
    // 明细-保存
    detailedSubmitForm () {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          const info = this.selectList.filter((item) => {
            return item.id === this.addForm.projectId;
          });
          const data = JSON.parse(JSON.stringify(this.addForm));
          console.log('addForm数据', data)
          data.projectName = info[0].projectName || info[0].businessTypeName;
          if (data.detailItemId) {
            const index = this.tableList.findIndex(item => {
              return item.id === data.detailItemId
            })
            this.tableList.splice(index, 1, data)
          } else {
            data.detailItemId = this.tableList.length + 1;
            // data.expenseTime = this.getDateTime.dateTimeStr('y-m-d h:i:s')
            this.tableList.push(data);
          }
          this.$nextTick(() => {
            this.addDialog = false;
          });
        }
      });
    },
    handleCloseDialog () {
      this.addForm = {}
      this.$refs.addForm.resetFields()
    },
    // 明细-编辑
    handleClickEdit (row) {
      this.handleChangeType(row.projectState)
      this.addDialog = true;
      this.$nextTick(() => {
        this.addForm = JSON.parse(JSON.stringify(row));
      });
    },
    // 明细-删除
    handleClickDel (index) {
      this.$confirm('是否删除此条数据', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableList.splice(index, 1)
      }).catch(() => {});
    },
    // 选中文件
    changeFile (file, filelist) {
      this.fileList = filelist;
      // this.$refs.upload.submit()
    },
    // 移除文件
    removeFile (file, filelist) {
      this.fileList = filelist;
    },
    // 文件上传成功
    handleFileSuccess (res) {
      console.log(res);
    },
    // 提交
    handleClickSubmit () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let arr = []
          this.fileList.forEach(item => {
            arr.push(item.response.data)
          })
          Reimbursement.add(this, {
            submitDto: {
              ...this.form,
              imgTu: JSON.stringify(arr)
            },
            submitDetailDtoList: this.tableList,
            flowTaskCommentDto: { approvalType: 'agree'},
            taskVariableData: {...this.getUserInfo}
          }).then(res => {
            this.$message.success('添加成功')
            this.$router.go(-1)
          })
        }
      });
    }
  }
};
</script>
<style scoped>
.add {
  position: relative;
}
.table-title {
  padding: 0px 5px;
  height: 22px;
  line-height: 22px;
  margin: 3px 0px;
  border-left: 3px solid rgb(64, 158, 255);
}
.flex {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
